<?php

namespace yunj\app\admin\controller\route;

use think\db\Query;
use think\facade\Db;
use yunj\app\admin\enum\IsDemo;
use yunj\app\admin\enum\route\RouteDataType;
use yunj\app\admin\enum\State;
use yunj\app\admin\controller\Controller;
use yunj\app\admin\enum\EnableLoginAuth;
use yunj\app\admin\service\route\page\RouteListService;
use yunj\app\admin\service\route\page\RouteAddService;
use yunj\app\admin\service\route\page\RouteEditService;
use yunj\app\admin\service\route\RouteService;
use yunj\core\builder\YunjForm;

class RouteController extends Controller {

    /**
     * @return RouteListService
     */
    private function getListService(): RouteListService {
        return app(RouteListService::class);
    }

    /**
     * @return RouteAddService
     */
    private function getAddService(): RouteAddService {
        return app(RouteAddService::class);
    }

    /**
     * @return RouteEditService
     */
    private function getEditService(): RouteEditService {
        return app(RouteEditService::class);
    }

    public function lists() {
        $builder = $this->getListService()->getListBuilder();
        $builder->assign();
        return view_table($builder);
    }

    public function add() {
        $builder = $this->getAddService()->getBuilder();
        $builder->assign();
        return $this->view('route/form', ['builderId' => $builder->getId()]);
    }

    public function edit() {
        $builder = $this->getEditService()->getBuilder();
        $builder->assign();
        return $this->view('route/form', ['builderId' => $builder->getId()]);
    }

    public function sort() {
        $args = [
            'field' => function (YunjForm $builder) {
                return [
                    "sort_tree" => [
                        "title" => "排序",
                        "type" => "tree",
                        "mode" => "edit",
                        "dragSort" => "level",
                        "nodeIdKey" => "id",
                        "nodePidKey" => "pid",
                    ]
                ];
            },
            'button' => function ($builder) {
                return ['reset', 'submit'];
            },
            'load' => function (YunjForm $builder) {
                $where = [['state', '=', State::NORMAL]];
                $order = ['sort' => 'asc', 'id' => 'asc'];
                $items = $this->getListService()->getListBuilderQuery()->where($where)->order($order)->field(['id', 'pid', 'name', 'type_txt'])->select()->toArray();
                $items = array_map(function ($item) {
                    $item['name'] = "【{$item['type_txt']}】" . handle_route_rule($item['name']);
                    return $item;
                }, $items);
                return [
                    'sort_tree' => $items
                ];
            },
            'submit' => function (YunjForm $builder, array $data) {
                $datas = [];
                $sort = 0;
                foreach ($data['sort_tree'] as $v) {
                    if (!($idVal = $v['id']) || !strstr($idVal, '_')) {
                        continue;
                    }
                    list($type, $id) = explode('_', $idVal);
                    if (!$type || !$id || !RouteDataType::isValue($type)) {
                        continue;
                    }
                    $datas[$type] = $datas[$type] ?? [];
                    $datas[$type][] = [
                        'id' => $id,
                        'sort' => $sort++,
                    ];
                }
                foreach ($datas as $type => $dbDatas) {
                    /** @var RouteDataType $typeObj */
                    $typeObj = RouteDataType::byValue($type);
                    $typeObj->getModel()->batchChange($dbDatas);
                }
                // 重置路由
                RouteService::reset();
                return success_json(['reload' => true]);
            }
        ];
        $builder = YF('RouteSort', $args);
        return view_form($builder);
    }

    // 下拉搜索路由分组选项
    public function dropdownSearchGroupOptions() {
        $param = input('get.');
        $ids = filter_sql($param['ids']);
        $keywords = filter_sql($param['keywords']);

        $where = [];
        if (!yunj_config('admin.use_demo')) {
            $query->where('is_demo', '=', IsDemo::NO);
        }
        if ($ids) {
            $where[] = ['id', 'in', $ids];
        } else {
            $where[] = ['system_key', 'is null'];   // 系统的不能选择
        }
        if ($keywords) $where[] = ['name|desc', 'like', "%{$keywords}%"];
        $field = ['id', 'full_name', 'full_desc'];
        $datas = self::getAdminRouteGroupModel()->getOwnRowsToArray($where, $field, ["id" => "desc"], 0, 20);
        $items = [];
        foreach ($datas as $data) {
            ['id' => $id, 'full_name' => $fullName, 'full_desc' => $fullDesc] = $data;
            $txt = $fullName;
            if ($fullDesc) {
                $txt .= "【{$fullDesc}】";
            }
            $items[] = ['id'=>$id,'name'=>$txt];
        }
        return success_json($items);
    }

    // 下拉搜索路由选项
    public function dropdownSearchRouteOptions() {
        $param = input('get.');
        $ids = filter_sql($param['ids']);
        $keywords = filter_sql($param['keywords']);

        $where = [];
        if (!yunj_config('admin.use_demo')) {
            $query->where('is_demo', '=', IsDemo::NO);
        }
        if ($ids) $where[] = ['id', 'in', $ids];
        if ($keywords) $where[] = ['name|desc|rule|route', 'like', "%{$keywords}%"];
        $field = ['id', 'name', 'full_desc', 'base_url', 'route'];
        $datas = self::getAdminRouteModel()->getOwnRowsToArray($where, $field, ["id" => "desc"], 0, 20);
        $items = [];
        foreach ($datas as $data) {
            ['id' => $id, 'full_desc' => $fullDesc, 'base_url' => $baseUrl, 'route' => $route] = $data;
            $txt = $baseUrl;
            if ($fullDesc) {
                $txt .= "【{$fullDesc}】";
            }
            $items[] = ['id'=>$id,'name'=>$txt];
        }
        return success_json($items);
    }

}